import React, { useEffect, useRef, useState } from 'react';
import { useDebounceFn, useClickAway } from 'ahooks';
import { Form, DatePicker, Select, Radio, Button, message, Checkbox } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { DownloadOutlined } from '#/utils/antdIcons.js';
import { PageLoading, TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { useStaticState, useTRState } from '#/utils/trHooks.jsx';

import { TRCheckboxModal, DimensionalSort } from '@/components/index.js';
import { exportGroup } from '@/utils/fileExport.js';
import { useRem } from '@/hooks/index.js';
import { getParamObj } from '@/utils/index.js';
import { getContractTypeCodes } from '@/pages/ETrade/ContractManagement/service';
import { TIME_24, TIME_96 } from '@/pages/ETrade/components/helper.js';

import BaseTable from './components/BaseTable';
import ContractChecked from './components/ContractChecked';
import { ChartDealElect } from './components/Charts/index.js';
import ContractModal from './components/ContractModal/index.jsx';
import {
  queryContractOptions,
  queryUnitOptions,
  queryContractPriceFluctuationData,
  queryContractAndStationInfo,
} from './services.js';
import { SELECT_DATA, OPTION_KEY, tableHead, powerTypeOption } from './helper';
import styles from './index.less';

const { RangePicker } = DatePicker;
const monthFormat = 'YYYYMMDD',
  dataInit = [moment().startOf('month'), moment().endOf('month')];

const MyStations = (props: any) => {
  const {
    value = [],
    onChange,
    // options = [],
    treeData = [],
    optionAll = [],
    className,
    disabled,
  } = props;
  const title = '交易单元';
  const isEmpty = !treeData.length;
  useEffect(() => {
    if (!value.length) {
      onChange(optionAll);
    }
  }, []);
  const onHandleModal = async () => {
    if (isEmpty || disabled) return;
    const result = await TRCheckboxModal.show({
      title,
      value,
      treeData,
    });
    if (result?.index === 1 && result.checkedKeys.length) {
      onChange(result.checkedKeys);
    }
    TRCheckboxModal.dismiss();
  };
  return (
    <div className={className}>
      <Select
        open={false}
        style={{
          width: 200,
        }}
        value={
          !value.length
            ? '请选择交易单元'
            : value.length === optionAll.length
            ? '全部'
            : `${value.length}项/${optionAll.length}项`
        }
        onClick={onHandleModal}
        onChange={onChange}
        disabled={disabled}
      />
    </div>
  );
};
const MyContracts = (props: any) => {
  const { value = [], onChange, options = [], treeData = [], className, multiple = true } = props;
  const title = '合约';
  const onHandleModal = async () => {
    // if (isEmpty) return;
    if (!treeData) return;
    const result = await ContractModal.show({
      title,
      value,
      treeData,
      multiple,
    });
    if (result?.index === 1 && result.checkedKeys.length) {
      onChange(result.checkedKeys);
    }
    ContractModal.dismiss();
  };
  return (
    <div className={className}>
      <Select
        value={
          !value.length
            ? '请选择合约'
            : value.length === options.length
            ? '全部'
            : `${value.length}项/${options.length}项`
        }
        style={{ width: '2rem' }}
        placeholder="请选择合约"
        options={options}
        open={false}
        showSearch={false}
        showArrow={true}
        onClick={onHandleModal}
        onChange={onChange}
      />
    </div>
  );
};
const ContractAnalysis = ({ menuCode, buttonPermissions }: any) => {
  const canEport =
    buttonPermissions.findIndex((item: any) => item.menuCode === 'ContractAnalysisExportButton') >
    -1;
  const [loading, setLoading] = useState(false),
    staticState = useStaticState({
      flag: false, //合约管理跳转
      isFirst: false, //默认请求
      str: null,
      contractOption: [],
    }),
    [listLoading, setListLoading] = useState(true),
    [tableDataSource, setTableDataSource] = useState([]), //主表格数据
    // [tableHeader, setTableHeader]: any = useState(), //表头
    [stations, setStations] = useState<any>([]), // 全部场站（平铺）
    [stationTree, setStationTree] = useState<any>([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState<any>([]), //全部场站(全选)
    [contractStations, setContractStations] = useState<any>([]), //全部合约
    [contractStationTree, setContractStationTree] = useState<any>([]), //合约树
    [param, setParam] = useState(SELECT_DATA), //灵活聚合项
    [form] = Form.useForm(),
    reSzie = useRem(1920),
    [echartsData, setEchartsData] = useState<any>({}),
    [echartsParam, setEchartsParam]: any = useState(), //图表筛选参数
    [dataLock, setDataLock] = useState(false),
    [dateArray, setDateArray] = useState<any>([]), //可选日期列表
    [filterUnitOptions, setFilterUnitOptions] = useState(), //父维度筛选 交易单元列表
    // [contractOptionsTree, setContractOptionsTree] = useState(),//父维度筛选 合约树
    [contractOptions, setContractOptions] = useState(), //父维度筛选 合约列表
    [dateTime, setDateTime] = useState<any>(), //父维度筛选 时间
    [contractDownOpen, setContractDownOpen] = useState(false), //父维度筛选框 合约下拉列表显示隐藏
    [downFocus, setDownFocus] = useState(false),
    [heYueDisable, setDisable] = useState(false),
    [paramsForm, setParamsForm] = useState<any>(),
    [queryForm, setQueryForm] = useState<any>({});
  // [exporting, setExporting] = useState(false);

  const [state, setState] = useTRState({
    contractTypeList: [],
    indeterminate: true,
    checkAll: false,
  });
  const staticData = useStaticState({
    formDate: {},
    provinceIds: [],
    contractTypeCodes: [],
    oldContractTypeCodes: [],
  });
  const groupRef = useRef(null);
  useClickAway(() => {
    downFocus && setContractDownOpen(false);
  }, [groupRef]);
  useEffect(() => {
    staticState.isFirst = true;
    staticState.str = getParamObj();
    if (
      JSON.stringify(staticState.str) !== '{}' &&
      decodeURIComponent(staticState.str.contractInfoList)?.length
    ) {
      staticState.flag = true;
      staticState.str.contractInfoList = JSON.parse(
        decodeURIComponent(staticState.str.contractInfoList),
      );
      form.setFieldsValue({
        date: [moment(staticState.str.beginDate), moment(staticState.str.endDate)],
        // contract: staticState.str.contractInfoList.map((t: any) => t.contractId)
      });
    }
    init();
  }, []);

  const setContractTypeCodes = async (list = []) => {
    staticData.provinceIds = [];
    stations?.forEach((s: any) => {
      // @ts-ignore
      if (list.includes(s?.value) && !staticData.provinceIds.includes(s?._regionCode)) {
        staticData.provinceIds.push(s._regionCode);
      }
    });
    const contractTypeRes = await getContractTypeCodes({ provinceIds: staticData.provinceIds });
    if (contractTypeRes?.statusCode === HttpCode.SUCCESS) {
      const contractTypeList: { label: any; value: any }[] = [];
      staticData.contractTypeCodes = [];
      contractTypeRes?.data?.forEach((d: any) => {
        if (!staticData.contractTypeCodes.includes(d?.contractTypeCode)) {
          staticData.contractTypeCodes.push(d?.contractTypeCode);
        }
        contractTypeList.push({
          label: d?.contractTypeName,
          value: d?.contractTypeCode,
        });
      });
      staticData.oldContractTypeCodes = _.cloneDeep(staticData.contractTypeCodes);
      setState({
        contractTypeList,
        checkAll: staticData.contractTypeCodes?.length === contractTypeList?.length,
        indeterminate:
          !!staticData.contractTypeCodes.length &&
          staticData.contractTypeCodes.length < contractTypeList.length,
      });
    }
  };
  //处理合约列表
  const getNewContractList = (data: any) => {
    if (!data) return;
    const _stations = [] as any;
    const _stationTree = [] as any;
    data.map((t: any) => {
      t.childrenContractList?.map((_t: any) => {
        _stations.push({
          ..._t,
          label: _t.contractName,
          value: t.contractId + '>' + _t.contractId,
        });
      });
      _stationTree.push({
        ...t,
        title: t.contractName,
        key: t.contractId,
        children: t.childrenContractList?.map((_t: any) => {
          return {
            ..._t,
            title: _t.contractName,
            key: t.contractId + '>' + _t.contractId,
          };
        }),
      });
      _stations.push({
        ...t,
        label: t.contractName,
        value: t.contractId,
      });
    });
    setContractStations(_stations);
    setContractStationTree(_stationTree);
    return _stations;
  };
  //请求合约列表
  const getContractList = async (values: any) => {
    //清空合约
    form.setFieldsValue({
      contract: [],
    });
    setContractStations([]);
    setContractStationTree(null);

    const startDate = moment(values.date ? values.date[0] : form.getFieldValue('date')[0]).format(
        'YYYY-MM-DD',
      ),
      endDate = moment(values.date ? values.date[1] : form.getFieldValue('date')[1]).format(
        'YYYY-MM-DD',
      ),
      stationIds = values.unit
        ? values.unit
        : form.getFieldValue('unit')?.length
        ? form.getFieldValue('unit')
        : optionAll;
    //处理交易单元id为单元名称
    setDisable(true);
    // const _temp = stations.filter((t: any) => stationIds.includes(t.value)).map((_t: any) => _t.label)
    const res = await queryContractOptions({
      contractEndDate: endDate,
      contractStartDate: startDate,
      stationIdList: stationIds,
      provinceIds: staticData.provinceIds, //省份id
      contractTypeCodes: staticData.contractTypeCodes, //类型code
      // stationNameList: _temp
    }).catch(() => {
      setLoading(false);
      setDisable(false);
    });
    setDisable(false);
    if (res.statusCode === HttpCode.SUCCESS) {
      const data = res.data;
      const _stations = getNewContractList(data || []);
      if (staticState.flag) {
        const _temp: any = [];
        staticState.str.contractInfoList.forEach(
          (_t: any) =>
            //只展示有权限的合约
            stations.some((t: any) => _t.stationId === t.value) && _temp.push(_t.contractId),
        );
        form.setFieldsValue({
          contract: _temp,
          contractTypeCodes: staticData.contractTypeCodes,
        });
        // form.setFieldsValue({
        //   contract: staticState.str.contractInfoList.map((t: any) => t.contractId),
        // });
        form.submit();
        staticState.flag = false;
      } else {
        form.setFieldsValue({
          contractTypeCodes: staticData.contractTypeCodes,
          contract: _stations
            .map((item: any) => {
              return `${item.contractId}`;
            })
            .splice(0, 100),
        });
        if (staticState.isFirst) {
          form.submit();
        }
      }
      staticState.isFirst = false;
    }
  };
  //默认勾选交易单元
  const defaultUnit = async () => {
    const _stations = stations
      .filter((item: any) => item._regionCode === stations?.[0]?._regionCode)
      .map((item: any) => item.value);
    if (!_stations.length) return;
    // 默认勾选山西省的交易单元
    form.setFieldsValue({
      unit: _stations,
    });
    await setContractTypeCodes(_stations);
    getContractList({ unit: _stations });
  };

  //所选合约是否有交易单元权限
  useEffect(() => {
    (async () => {
      if (!!stations.length) {
        if (staticState.flag) {
          const _temp: any = [];
          //是否有交易单元合约权限
          let cover;
          staticState.str.contractInfoList.map(
            (_t: any) =>
              stations.some((t: any) => _t.stationId === t.value) &&
              (!_temp.includes(_t.stationId) && _temp.push(_t.stationId), (cover = true)),
          );
          if (_temp.length) {
            //勾选有权限的交易单元
            form.setFieldsValue({
              unit: _temp,
            });
            await setContractTypeCodes(_temp);
            getContractList({ unit: _temp });
          }
          //没有数据权限
          if (!cover) {
            staticState.flag = false;
            setDataLock(true);
          }
        } else {
          defaultUnit();
        }
      }
    })();
  }, [stations]);

  // useEffect(() => {

  //   if (staticState.flag && !!contractStations.length) {
  //     staticState.flag = false;
  //     const _temp: any = [];
  //     staticState.str.contractInfoList.map(
  //       (_t: any) =>
  //         //只展示有权限的合约
  //         stations.some((t: any) => _t.stationId === t.value) && _temp.push(_t.contractId),
  //     );
  //     form.setFieldsValue({
  //       contract: _temp,
  //     });
  //     form.submit();
  //   }
  // }, [contractStations]);

  /** handle data */
  async function init() {
    // 获取数据权限
    setLoading(true);
    const res = await queryUnitOptions({ menuCode }).catch(() => setLoading(false));
    if (res?.statusCode === HttpCode.SUCCESS) {
      // setErrorMsg('');
      initDataPower(res?.data);
    } else {
      // setErrorMsg(res?.message);
    }
    setLoading(false);
  }

  function initDataPower(data = [] as any) {
    // 处理数据权限
    if (!data) {
      // setErrorMsg('暂无数据权限');
      return;
    }
    // regions = [];
    const _stations = [] as any;
    const _optionAll = [] as any;
    data.map((x: any) => {
      // 公司
      (x?.children || []).map((y: any) => {
        // 省份
        (y?.children || []).map((z: any) => {
          // 场站
          const temp = {
            _regionCode: x.value,
            _regionName: x.label,
            _companyCode: y.value,
            _companyName: y.label,
            _stationCode: z.value,
            _stationName: z.label,
            label: z.label,
            value: z.value,
          };
          _stations.push(temp);
          _optionAll.push(z.value);
        });
      });
    });
    setOptionAll(_optionAll);
    const _stationTree: any = [];
    const _groups = _.groupBy(_stations, '_regionName');
    for (const key in _groups) {
      const _group = _groups[key];
      //去重 根据_companyName
      const temp: any = [];
      const children = _group
        .filter((item: any) => !temp.includes(item._companyName) && temp.push(item._companyName))
        .map((item: any) => {
          return {
            title: item._companyName,
            key: Math.random(),
            children: _group
              .map((t: any) => {
                if (item._companyName == t._companyName) {
                  return {
                    title: t._stationName,
                    key: t._stationCode,
                  };
                }
              })
              .filter((t: any) => t),
          };
        });
      _stationTree.push({
        title: key,
        key: _group[0]._regionCode,
        children: children,
      });
    }
    setStations(_stations);
    setStationTree(_stationTree);
  }

  //取出默认第一行 最后一个子维度 作为echarts的横坐标
  const _getXAXIS = (data: any, arr: any[]) => {
    const _temp: any[] = [];
    const recursion = (item: any, index: number): any[] => {
      if (item[0]?.tag === '合约') {
        _temp.push({
          contractId: item[0]?.contractId,
          tag: item[0]?.tag,
          title: item[0]?.title,
          list: item.map((t: any) => ({ label: t.title, value: t.contractId })),
        });
      } else {
        _temp.push({
          tag: item[0]?.tag,
          title: item[0]?.title,
          list: item.map((t: any) => ({ label: t.title, value: t.title })),
        });
      }
      if (item[0]?.children instanceof Array && item.length > 0) {
        return recursion(item[0].children, index - 1);
      }
      return _temp;
    };
    return recursion(data, arr.length - 1);
  };

  //根据父维度 筛选出图表所需数据  return:最后一个维度数组
  const _getFilterXAXIS = (data: any, arr: any[]): any[] => {
    const _echartsParam = _.cloneDeep(echartsParam);
    //取最后一个维度 第一行数据
    const recursion = (item: any, index: number): any[] => {
      const _item: any[] = [];
      item.forEach((t: any) => {
        if (t.title === '合计') return;
        _item.push(t);
      });
      let _temp: any[] = [];
      //如果已经是最后一个维度
      if (arr.length - 1 <= index) {
        return _item;
      }
      _item.forEach((t: any) => {
        if (t.tag === '合约') {
          t.contractId === _echartsParam[OPTION_KEY[arr[index]]] &&
            (_temp = recursion(t.children, index + 1));
        } else {
          t.title === _echartsParam[OPTION_KEY[arr[index]]] &&
            (_temp = recursion(t.children, index + 1));
        }
      });
      return _temp;
    };
    return recursion(data, 0);
  };

  //处理表格数据 dataSource表格数据 postdata选项
  const getNewDataSource = (dataSource: any, order: any, specialData: any, point: string) => {
    const formatForTable = (item: any, optionName: any, index = 0) => {
      const arr: any[] = [];
      let contractExecute: any;
      Object.entries(item).map((t: any) => {
        if (t[0] === 'total') {
          return;
        }
        if (optionName[index] === '合约') {
          contractExecute = specialData.contractInfos.find(
            (_t: any) => _t.stationId == t[0].split(',')[2] && _t.contractId === t[0].split(',')[1],
          );
        }
        let obj: any = {};
        //最后一个维度为数组
        if (t[1] instanceof Array) {
          obj = {
            statisticalPrice: t[1][0], //统计电费 不展示
            statisticalElectricity: parseFloat(t[1][1]).toFixed(3),
            title:
              optionName[index] === '时点'
                ? point === '24'
                  ? TIME_24[t[0] - 1]
                  : TIME_96[t[0] - 1]
                : optionName[index] === '日期'
                ? t[0].replaceAll('-', '')
                : optionName[index] === '合约'
                ? t[0].split(',')[0]
                : t[0],
            tag: optionName[index],
            averagePrice: parseFloat(t[1][2]).toFixed(2),
            installedCapacity:
              optionName[index] === '交易单元' &&
              parseFloat(
                specialData.stationInfos.find((_t: any) => _t.stationName === t[0])
                  ?.stationCapacity + '',
              ).toFixed(2),
            contractExecute:
              optionName[index] === '合约' &&
              moment(contractExecute?.contractStartDate).format('YYYYMMDD') +
                '-' +
                moment(contractExecute?.contractEndDate).format('YYYYMMDD'),
            contractAmount:
              optionName[index] === '合约' &&
              parseFloat(contractExecute?.totalContractQuantity).toFixed(3),
          };
          if (optionName[index] === '合约') {
            obj.contractId = t[0].split(',')[2] + '>' + t[0].split(',')[1];
          }
          arr.push(obj);
          return;
        }
        obj = {
          statisticalPrice: t[1].total[0],
          statisticalElectricity: parseFloat(t[1].total[1]).toFixed(3),
          title:
            optionName[index] === '时点'
              ? point === '24'
                ? TIME_24[t[0] - 1]
                : TIME_96[t[0] - 1]
              : optionName[index] === '日期'
              ? t[0].replaceAll('-', '')
              : optionName[index] === '合约'
              ? t[0].split(',')[0]
              : t[0],
          tag: optionName[index],
          averagePrice: parseFloat(t[1].total[2]).toFixed(2),
          installedCapacity:
            optionName[index] === '交易单元' &&
            parseFloat(
              specialData.stationInfos.find((_t: any) => _t.stationName === t[0])?.stationCapacity +
                '',
            ).toFixed(2),
          contractExecute:
            optionName[index] === '合约' &&
            moment(contractExecute?.contractStartDate).format('YYYYMMDD') +
              '-' +
              moment(contractExecute?.contractEndDate).format('YYYYMMDD'),
          contractAmount:
            optionName[index] === '合约' &&
            parseFloat(contractExecute?.totalContractQuantity).toFixed(3),
        };
        if (optionName[index] === '合约') {
          obj.contractId = t[0].split(',')[2] + '>' + t[0].split(',')[1];
        }
        let children: any[] = [];
        children = children.concat(formatForTable(t[1], optionName, index + 1));
        obj.children = children;
        arr.push(obj);
      });
      arr.sort((a: any, b: any) => {
        if (optionName[index] === '交易单元' || optionName[index] === '合约') {
          return a.title.localeCompare(b.title, 'zh-CN');
        }
        //默认时点排序方式
        return a.title > b.title ? 1 : -1;
      });
      return arr;
    };
    const total: any = {
      title: '合计',
      tag: order[0],
      statisticalPrice: dataSource.data.total[0],
      statisticalElectricity: parseFloat(dataSource.data.total[1]).toFixed(3),
      averagePrice: parseFloat(dataSource.data.total[2]).toFixed(2),
      children: [],
      installedCapacity: false,
      contractExecute: false,
      contractAmount: false,
    };
    // 添加合计行
    const result = [total, ...formatForTable(dataSource.data, order)];
    return result;
  };
  //请求表格数据
  const _fetchFile = async (postdata: any, { unit, date, point }: any) => {
    setListLoading(true);
    setTableDataSource([]);
    //请求交易单元和合约特殊值 参数
    const _param = {
      contractInfoList: contractStations
        .filter((t: any) => form.getFieldValue('contract').includes(t.value))
        .map((t: any) => {
          return {
            contractId: t.contractId,
            stationId: t.stationId,
          };
        }),
    };
    const res = await Promise.all([
      queryContractPriceFluctuationData(postdata),
      queryContractAndStationInfo(_param),
    ]);
    if (res[0].statusCode === HttpCode.SUCCESS && res[1].statusCode === HttpCode.SUCCESS) {
      const specialData = res[1].data;
      const data: any = getNewDataSource(res[0].data || [], postdata.order, specialData, point);
      setTableDataSource(data);
      if (data.length) {
        const _data = _.cloneDeep(data);
        //设置图表数据
        const _echarsData = _getXAXIS(_data.splice(1), SELECT_DATA);
        //设置父维度列表值
        const findUnit = postdata.order.includes('交易单元'),
          findDate = postdata.order.includes('日期'),
          findContract = postdata.order.includes('合约'),
          findTimeOrder = postdata.order.includes('时点');

        const _unitOptions =
          postdata.order.indexOf('交易单元') === 0
            ? _echarsData.find((_t) => _t.tag === '交易单元').list
            : (unit?.length ? unit : optionAll)
                .map((t: any) => {
                  const item = stations.find((_t: any) => t == _t._stationCode);
                  return {
                    label: item._stationName,
                    value: item._stationName,
                  };
                })
                .sort((a: any, b: any) => a.label.substr(0, 1).localeCompare(b.label.substr(0, 1)));
        const _temp =
          postdata.order.indexOf('合约') > -1 &&
          postdata.order.indexOf('合约') < postdata.order.indexOf('交易单元')
            ? staticState.contractOption
                .filter(
                  (t: any) =>
                    t.contractName === _echarsData.find((_t) => _t.tag === '合约').title + '',
                )
                .map((t: any) => ({ value: t.stationName, label: t.stationName }))
            : _unitOptions;
        setFilterUnitOptions(_temp);

        const _contractOptions =
          postdata.order.indexOf('交易单元') > -1 &&
          postdata.order.indexOf('合约') > postdata.order.indexOf('交易单元')
            ? staticState.contractOption.filter(
                (t: any) =>
                  t.stationName ===
                  (findUnit && _echarsData.find((_t) => _t.tag === '交易单元').title + ''),
              )
            : postdata.order.indexOf('合约') === 0
            ? staticState.contractOption.filter((t: any) =>
                _echarsData
                  .find((_t) => _t.tag === '合约')
                  .list.some((_t: any) => _t.value === t.value),
              )
            : staticState.contractOption;

        setContractOptions(_contractOptions);
        setDateTime(date);
        setDateArray(
          postdata.order.indexOf('日期') === 0
            ? _echarsData.find((_t) => _t.tag === '日期').list.map((t: any) => t.value)
            : [],
        );
        //设置父维度选择默认值【合约量价图】默认：第一个维度
        setEchartsParam({
          type: '电力',
          date:
            findDate && moment(_echarsData.find((t) => t.tag === '日期').title).format('YYYYMMDD'),
          unit: findUnit && _echarsData.find((t) => t.tag === '交易单元').title + '',
          timeOrder: findTimeOrder && point === '24' ? '0100' : '0015',
          contract: findContract && _echarsData.find((t) => t.tag === '合约').contractId,
        });
      }
    }
    setListLoading(false);
  };

  //获取默认第一行 根据传入维度递归获取数据
  const _getDimensionData = (data: any, deepIndex: number): any[] => {
    if (deepIndex) {
      return _getDimensionData(
        data[0].children.length ? data[0].children : data[1].children,
        deepIndex - 1,
      );
    }
    return data;
  };

  const onexport = async () => {
    if (!tableDataSource.length) return;
    if (!canEport) {
      return message.info('请联系管理员获取相关权限');
    }
    const columns = tableHead.map((x) => ({
      header: x.name,
      key: x.field,
    }));
    exportGroup(tableDataSource, columns, '合约分析');
  };
  //根据筛选参数 重绘图表
  const repaint = () => {
    const _echarsData = _getFilterXAXIS(tableDataSource, param);
    setEchartsData({
      XAXIS: _echarsData.map((t) => t.title),
      totalStatementQuantity: _echarsData.map(
        (t) =>
          t.statisticalElectricity *
          (queryForm.point === '24' || echartsParam.type === '电量' ? 1 : 4),
      ),
      averagePrice: _echarsData.map((t) => t.averagePrice),
    });
  };
  useEffect(() => {
    if (tableDataSource.length) {
      repaint();
    }
  }, [echartsParam]);

  const _onFinish = useDebounceFn(
    (values: any) => {
      if (values.contract.length > 2000) {
        return message.error('请选择小于2000条合约数据查询');
      }
      // 查询
      const startDate = moment(values.date[0]).format('YYYY-MM-DD'),
        endDate = moment(values.date[1]).format('YYYY-MM-DD');
      // stationIds = values.unit.length || optionAll;
      setParam(SELECT_DATA); //初始化聚合维度
      setDataLock(false);
      const contractList = contractStations
        .filter((t: any) => values.contract.includes(t.value))
        .map((t: any) => ({ ...t, value: t.stationId + '>' + t.contractId }));
      staticState.contractOption = contractList;
      const _queryForm = { ...values, provinceIds: staticData.provinceIds };
      setQueryForm(_queryForm);
      const _params = JSON.stringify({
        contractInfoList: contractList.map((t: any) => ({
          contractId: t.contractId,
          contractName: t.contractName,
          stationName: t.stationName,
          stationId: t.stationId,
        })),
        timeOrderType: values.point,
        contractStartDate: startDate,
        contractEndDate: endDate,
      });
      setParamsForm(_params);
      _fetchFile(
        {
          order: SELECT_DATA,
          param: _params,
        },
        _queryForm,
      );
    },
    { wait: 500 },
  );
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      setTableDataSource([]);
      staticState.isFirst = true;
      defaultUnit();
    },
    { wait: 500 },
  );

  const onCheckAllChange = (e: any) => {
    staticData.contractTypeCodes = [];
    if (e.target.checked) {
      state.contractTypeList?.forEach((c: any) => {
        staticData.contractTypeCodes.push(c?.value);
      });
    }

    form &&
      form.setFieldsValue({
        ...form.getFieldsValue(),
        contractTypeCodes: staticData.contractTypeCodes,
      });
    setState({
      checkAll: e.target.checked,
      indeterminate: false,
    });
  };

  const onCheckChange = (obj: any = {}) => {
    let checkedList = _.cloneDeep(staticData.contractTypeCodes);
    if (checkedList.includes(obj?.value)) {
      checkedList = checkedList?.filter((c: any) => c !== obj?.value);
    } else {
      checkedList.push(obj?.value);
    }

    staticData.contractTypeCodes = _.cloneDeep(checkedList);
    form && form.setFieldsValue({ ...form.getFieldsValue(), contractTypeCodes: checkedList });
    setState({
      checkAll: staticData.contractTypeCodes?.length === state.contractTypeList?.length,
      indeterminate:
        !!staticData.contractTypeCodes.length &&
        staticData.contractTypeCodes.length < state.contractTypeList.length,
    });
  };

  const _renderHeader = () => {
    const initialValues = () => {
      return {
        date: dataInit,
        point: '96',
      };
    };
    //切换日期 交易单元 刷新合约列表
    const _formOnChange = async (values: any) => {
      staticData.formDate = values;
      if (!values.point && !values.contract) {
        if (values.unit?.length) {
          await setContractTypeCodes(values.unit);
          getContractList(values);
        }
        if (values.contractTypeCodes) {
          staticData.contractTypeCodes = _.cloneDeep(values.contractTypeCodes);
          staticData.oldContractTypeCodes = _.cloneDeep(values.contractTypeCodes);
          setState({
            checkAll: staticData.contractTypeCodes?.length === state.contractTypeList?.length,
            indeterminate:
              !!staticData.contractTypeCodes.length &&
              staticData.contractTypeCodes.length < state.contractTypeList.length,
          });
          getContractList({ unit: form.getFieldValue('unit') || [] });
        }
      }
    };
    const onOpenChange = (open: boolean) => {
      if (!open && staticData.formDate.date) {
        getContractList(staticData.formDate);
      }
    };

    return (
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
          onValuesChange={_formOnChange}
        >
          <Form.Item name="date" className={styles.cell_item}>
            <RangePicker
              disabled={heYueDisable}
              className={styles.select_date}
              format={'YYYYMMDD'}
              separator={'-'}
              onOpenChange={onOpenChange}
            />
          </Form.Item>
          <Form.Item name="unit" className={styles.cell_item}>
            <MyStations
              disabled={heYueDisable}
              options={stations}
              treeData={stationTree}
              optionAll={optionAll}
            />
          </Form.Item>
          <Form.Item name="contractTypeCodes" className={styles.cell_item}>
            <React.Fragment>
              <Select
                disabled={heYueDisable}
                className={styles.select_contractType}
                placeholder="请选择合约类型"
                options={state.contractTypeList}
                value={
                  !staticData.contractTypeCodes?.length
                    ? '请选择合约类型'
                    : state.checkAll
                    ? '全部合约类型'
                    : `${staticData.contractTypeCodes?.length}项/${state.contractTypeList?.length}项`
                }
                onDropdownVisibleChange={(open) => {
                  if (
                    !open &&
                    staticData.contractTypeCodes?.length &&
                    !_.isEqual(staticData.oldContractTypeCodes, staticData.contractTypeCodes)
                  ) {
                    getContractList(form.getFieldsValue());
                    staticData.oldContractTypeCodes = _.cloneDeep(staticData.contractTypeCodes);
                  }
                }}
                dropdownClassName={styles.contractDropdown}
                dropdownRender={() => {
                  return (
                    <div className={styles.contractDropdown_container}>
                      <Checkbox
                        indeterminate={state.indeterminate}
                        onChange={onCheckAllChange}
                        checked={state.checkAll}
                      >
                        全选
                      </Checkbox>
                      <div className={styles.contractDropdown_container_label}>
                        {state.contractTypeList?.map((c: any) => {
                          return (
                            <Checkbox
                              onChange={() => onCheckChange(c)}
                              checked={staticData.contractTypeCodes.includes(c?.value)}
                              key={c?.value}
                              style={{ marginTop: 10 }}
                            >
                              {c?.label ?? ''}
                            </Checkbox>
                          );
                        })}
                      </div>
                    </div>
                  );
                }}
              />
            </React.Fragment>
          </Form.Item>
          <Form.Item
            name="contract"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择合约' }]}
          >
            <MyContracts options={contractStations} treeData={contractStationTree} />
          </Form.Item>
          <Form.Item name="point" className={styles.cell_item}>
            <div className={styles.point}>
              <Radio.Group defaultValue="96" buttonStyle="solid" size="small">
                <Radio.Button value="24">24</Radio.Button>
                <Radio.Button value="96">96</Radio.Button>
              </Radio.Group>
            </div>
          </Form.Item>
          <Button className={styles.submit} type="primary" htmlType="submit">
            查询
          </Button>
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
          <div
            className={`${styles.import} ${
              (!tableDataSource.length || !canEport) && styles.disabled
            }`}
            onClick={onexport}
          >
            <DownloadOutlined style={{ fontSize: '0.12rem' }} />
            导出
          </div>
        </Form>
      </div>
    );
  };
  //表格图表内容区域渲染
  const _renderContent = () => {
    if (listLoading) return <PageLoading />;
    if (dataLock) return <TRDefault type="lock" />;
    if (!tableDataSource.length) return <TRDefault type="empty" />;
    /*获取设置选择器下拉列表项*/
    //时点
    const _data = _.cloneDeep(tableDataSource);
    const pointOptions =
      param.includes('时点') && param.indexOf('时点') < param.length - 1
        ? _getDimensionData(_data.splice(1), param.indexOf('时点')).map((t) => ({
            label: t.title,
            value: t.title,
          }))
        : [];

    //重新聚合
    const _polymerize = (options: any) => {
      setParam(options);
      _fetchFile(
        {
          order: options,
          param: paramsForm,
        },
        queryForm,
      );
    };

    const _selectContractOnChange = (value: any) => {
      const _temp = {
        ...echartsParam,
        contract: value[0],
      };
      //根据选项筛选交易单元
      if (param.indexOf('交易单元') > -1 && param.indexOf('合约') < param.indexOf('交易单元')) {
        const _unitOptions = stations
          .filter((t: any) => t.value == value[0].split('>')?.[0])
          .map((t: any) => ({ value: t.label, label: t.label }));
        setFilterUnitOptions(_unitOptions);
        _temp.unit = _unitOptions?.[0]?.value;
      }
      setEchartsParam(_temp);
    };

    const _selectUnitOnChange = (value: any) => {
      const _temp = {
        ...echartsParam,
        unit: value,
      };
      //根据选项筛选合约
      if (param.indexOf('合约') > -1 && param.indexOf('合约') > param.indexOf('交易单元')) {
        const _contractOptions = staticState.contractOption.filter(
          (t: any) => t.stationName === value,
        );
        setContractOptions(_contractOptions);
        _temp.contract = _contractOptions?.[0]?.value;
      }
      setEchartsParam(_temp);
    };
    const _selectDateOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        date: value.format('YYYYMMDD'),
      });
    };
    const _selectPointOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        timeOrder: value,
      });
    };
    const onTypeChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        type: value,
      });
    };
    //控制日历可选范围
    const disabledDate = (current: any) => {
      const _date = dateTime;
      return (
        (current && (current < _date[0].startOf('day') || current > _date[1].endOf('day'))) ||
        (dateArray.length && !dateArray.includes(moment(current).format('YYYYMMDD')))
      );
    };
    const showType = queryForm.point === '96' && param[param.length - 1] === '时点';
    const isPower = showType && echartsParam.type === '电力';
    return (
      <>
        <div className={styles.leftBox}>
          <DimensionalSort
            reSize={reSzie}
            optionsArray={SELECT_DATA}
            option={param}
            onClick={_polymerize}
          />
          <BaseTable tableData={tableDataSource} tableHeader={tableHead} />
        </div>
        <div className={styles.rightBox}>
          <div className={styles.filter_group}>
            <div className={styles.title}>合约量价图</div>
            <div className={styles.flex}>
              {showType ? (
                <Select
                  className={styles.filter_unit}
                  placeholder="选择类型"
                  onChange={onTypeChange}
                  value={echartsParam.type}
                  options={powerTypeOption}
                />
              ) : (
                ''
              )}

              {param.map((t: any, i: number) => {
                if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_unit}
                        showSearch
                        placeholder="选择交易单元"
                        onChange={_selectUnitOnChange}
                        value={echartsParam.unit}
                        // onSearch={onSearch}
                        options={filterUnitOptions}
                        filterOption={(input, option) => {
                          return (option?.label as unknown as string)
                            .toLowerCase()
                            .includes(input.toLowerCase());
                        }}
                      />
                    );
                  }
                }
                if (t === '日期' && param[param.length - 1] !== '日期') {
                  {
                    return (
                      <DatePicker
                        key={i}
                        onChange={_selectDateOnChange}
                        inputReadOnly
                        allowClear={false}
                        className={styles.filter_date}
                        value={moment(echartsParam.date)}
                        format={monthFormat}
                        disabledDate={disabledDate}
                      />
                    );
                  }
                }
                if (t === '合约' && param[param.length - 1] !== '合约') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_contract}
                        value={echartsParam.contract}
                        options={contractOptions}
                        style={{ width: 216 }}
                        open={contractDownOpen}
                        onBlur={() => {
                          setDownFocus(true);
                        }}
                        placeholder="请选择合约"
                        onChange={_selectContractOnChange}
                        onClick={() => {
                          setContractDownOpen(true);
                          setDownFocus(false);
                        }}
                        dropdownRender={() => (
                          <ContractChecked
                            ref={groupRef}
                            setOpen={setContractDownOpen}
                            options={contractOptions}
                            onChange={_selectContractOnChange}
                            value={echartsParam.contract}
                          />
                        )}
                      />
                    );
                  }
                }
                if (t === '时点' && param[param.length - 1] !== '时点') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_point}
                        placeholder="选择时点"
                        onChange={_selectPointOnChange}
                        value={echartsParam.timeOrder}
                        options={pointOptions}
                      />
                    );
                  }
                }
              })}
            </div>
          </div>
          <div style={{ height: 'calc(100vh - 2.31rem)', width: '100%' }}>
            {!echartsData?.XAXIS?.length ? (
              <TRDefault type="empty" />
            ) : (
              <ChartDealElect data={echartsData} scale={reSzie / 100} isPower={isPower} />
            )}
          </div>
        </div>
      </>
    );
  };
  if (loading) return <PageLoading />;
  return (
    <>
      {_renderHeader()}
      <div className={styles.content_body}>
        <div className={styles.title}>合约分析</div>
        <div className={styles.content}> {_renderContent()}</div>
      </div>
    </>
  );
};
export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(ContractAnalysis);
